package socdev.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Handler;


public class UsersContainer implements Runnable{

	Map<String, User> users = new HashMap<String, User>();
	
	static boolean isUpdating;
	Handler handler;
	Runnable handlerRunnable;
	
	public UsersContainer() {
		isUpdating = false;
	}
	
	public synchronized void update() {
		if (isUpdating)
			return;
		isUpdating = true;
		new Thread(this).start();
		
	}
	
	public synchronized void update(Handler handler, Runnable runnable) {
		if (isUpdating)
			return;
		isUpdating = true;

		this.handler = handler;
		this.handlerRunnable = runnable;
		new Thread(this).start();

	}

	@Override
	public void run() {
		try {

			JSONArray jsonArray = JSonDownloader.getData("http://socdev-dev1.appspot.com/api/users/");
			users = new HashMap<String, User>();
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				User user = User.createFromJson(jsonObject);
				users.put(user.getId(), user);

			}
		
		}catch (JSONException e) {
			e.printStackTrace();
		}
		isUpdating = false;
	}
	
	public boolean contains(String nick) {
		return users.containsKey(nick);
		
	}
	
	public User get(String nick) {
		return users.get(nick);
	}
	

	public List<User> getAll() {
		return new ArrayList<User>(users.values());

	}
	
	
	
	
}
